import os

# 原始文件夹路径
original_folder = r'D:\BaiduNetdiskDownload\M4x100IMF\Annotations'
# 新的文件夹路径
new_folder = r'C:\Users\Y07\Desktop\yolov8-pytorch-master\VOCdevkit\VOC2007\Annotations'

# 定义替换函数
def replace_folder_path_in_xml(file_content, old_path, new_path):
    folder_pattern = f'<folder>{old_path}</folder>'
    new_content = file_content.replace(folder_pattern, f'<folder>{new_path}</folder>')
    return new_content

# 处理单个文件
def process_file(file_path, old_folder, new_folder):
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()
    new_content = replace_folder_path_in_xml(content, original_folder, new_folder)
    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(new_content)
    print(f'Processed file: {file_path}')

# 处理文件夹内的所有XML文件
def process_folder(folder_path, old_folder, new_folder):
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.lower().endswith('.xml'):
                file_path = os.path.join(root, file)
                process_file(file_path, old_folder, new_folder)

# 指定要处理的文件夹路径
folder_path = 'VOCdevkit/VOC2007/Annotations'  # 替换为你的XML文件所在的文件夹路径
process_folder(folder_path, original_folder, new_folder)
# import os
# import re
#
# # 处理文件夹内的所有XML文件
# def process_folder(folder_path):
#     # 遍历指定文件夹
#     for root, dirs, files in os.walk(folder_path):
#         for file in files:
#             if file.lower().endswith('.xml'):
#                 # 构造完整的文件路径
#                 file_path = os.path.join(root, file)
#                 # 读取文件内容
#                 with open(file_path, 'r', encoding='utf-8') as file_reader:
#                     content = file_reader.read()
#                 # 获取不带扩展名的文件名
#                 file_name_without_extension = os.path.splitext(file)[0]
#                 # 替换所有<filename>标签内容为不带扩展名的文件名加上.jpg
#                 new_content = re.sub(r'<filename>.*?</filename>', f'<filename>{file_name_without_extension}.jpg</filename>', content)
#                 # 写入修改后的内容
#                 with open(file_path, 'w', encoding='utf-8') as file_writer:
#                     file_writer.write(new_content)
#                 print(f'Processed file: {file_path}')
#
# # 指定要处理的文件夹路径
# folder_path = 'VOCdevkit/VOC2007/Annotations'  # 替换为你的XML文件所在的文件夹路径
# process_folder(folder_path)